﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tasks.Common.Entitys;
using Tasks.UI.Models.Article;
using Tasks.Business;
using Tasks.Core;
using Tasks.Common.Enum;
using Tasks.Common;
using System.Collections;
using System.IO;

using System.Net.Mail;
namespace Tasks.UI.Controllers
{
    public class BugController : BaseController
    {
        ArticleBLL arBll = new ArticleBLL();


        //public ActionResult DeleteBug(int id, string returnUrl)
        //{
        //    if (id != 0)//数据删除
        //    {
        //        arBll.DeleteArticle(id);
        //    }

        //    return Redirect(returnUrl);
        //}

        public ActionResult BugList(ArticleModel model)
        {
            #region "处理动作"

            if (model.act == "delete")
            {
                arBll.DeleteArticle(model.ID);
            }

            if (model.act == "testpass" && model.ArticleIDs != null)
            {
                TaskService.UpdateTestResult(model.ArticleIDs, TestResult.Pass, Config.CurrentOperator.Name);
            }

            if (model.act == "testnopass" && model.ArticleIDs != null)
            {
                TaskService.UpdateTestResult(model.ArticleIDs, TestResult.NoPass, Config.CurrentOperator.Name);
            }

            if (model.act == "applytest" && model.ArticleIDs != null)
            {
                TaskService.UpdateTestResult(model.ArticleIDs, TestResult.ApplyTest, Config.CurrentOperator.Name);
            }

            #endregion

            int rowCount = 0;
            model.PageSize = model.PageSize == 0 ? 15 : model.PageSize;
            model.PageIndex = model.PageIndex == 0 ? 1 : model.PageIndex;
            model.Type = model.Type == 0 ? (int)ArticleType.Task : model.Type;

            Hashtable condition = new Hashtable();
            condition["OwnerID"] = Config.CompanyID;
            condition["States"] = model.State == 0 ? "" : model.State.ToString();
            condition["ProjectID"] = model.ProjectID;
            condition["CreateUserID"] = model.CreateUserID;
            condition["OperatorID"] = model.OperatorID;
            condition["InTime1"] = model.InTime1;
            condition["InTime2"] = model.InTime2;
            condition["Type"] = model.Type;
            if (model.State == 5) { condition["States"] = "1,2"; }

            model.Articles = arBll.Search(condition, model.PageIndex, model.PageSize, out rowCount);
            model.RowCount = rowCount;
            if (model.Articles == null)
                model.Articles = new List<Article>();

            return View("/Views/Bug/BugList.cshtml", model);
        }

        [ActionName("View"), HttpPost]
        public ActionResult doView(ArticleModel model)
        {
            Article ar = arBll.GetArticleByID(model.ID);
            //添加回复
            ReplyArticle rep = new ReplyArticle();
            rep.ArticleID = model.ID;
            rep.Content = model.ReplyContent;
            rep.ReplyTime = DateTime.Now;
            rep.ParentID = Config.CurrentOperator.UserID;
            ar.ID = model.ID;

            ExecuteResult result = arBll.ModifyAll(ar, rep);
            return RedirectToAction("View", new { ID = model.ID, SendCode = 1, Message = model.Message, MessageType = (int)model.MessageType });
        }

        public ActionResult Edit(ArticleModel model)
        {
            model.PracticalStartTime = model.PracticalStartTime == null ? DateTime.Now.ToShortDateString() : model.PracticalStartTime;
            model.PracticalEndtTime = model.PracticalEndtTime == null ? DateTime.Now.ToShortDateString() : model.PracticalEndtTime;
            model.PlanStartTime = model.PlanStartTime == null ? DateTime.Now.ToShortDateString() : model.PlanStartTime;
            model.PlanEndTime = model.PlanEndTime == null ? DateTime.Now.ToShortDateString() : model.PlanEndTime;
            model.Type = model.Type == 0 ? (int)ArticleType.Task : model.Type;

            if (model.ID != 0)
            {
                Article ar = arBll.GetArticleByID(model.ID);
                model.Title = ar.Title;
                model.Content = ar.Content;
                model.PracticalStartTime = FormatTime(ar.PracticalStartTime);
                model.PracticalEndtTime = FormatTime(ar.PracticalEndtTime);
                model.PlanStartTime = FormatTime(ar.PlanStartTime);
                model.PlanEndTime = FormatTime(ar.PlanEndTime);
                model.State = ar.State;
                model.ProjectID = ar.ProjectID;
                model.OperatorID = ar.OperatorID;
                model.CreateUserName = ar.CreateUserName;
                model.CreateTime = ar.CreateTime;
                model.Images = ar.Images;
                model.IsTop = ar.IsTop == 1 ? true : false;
                model.Type = ar.Type;
                model.OperatorName = ar.OperatorName;


            }
            Session["ArticleModel"] = model;
            return View("/Views/Bug/Edit.cshtml", model);
        }

        [ActionName("Edit"), HttpPost]
        public ActionResult doEdit(ArticleModel model)
        {
            Article ar = new Article();
            if (model.ID != 0)
                ar = arBll.GetArticleByID(model.ID);
            ar.Title = model.Title;
            ar.Content = model.Content;
            ar.PracticalStartTime = Convert.ToDateTime(model.PracticalStartTime);
            ar.PracticalEndtTime = Convert.ToDateTime(model.PracticalEndtTime);
            ar.PlanStartTime = Convert.ToDateTime(model.PlanStartTime);
            ar.PlanEndTime = Convert.ToDateTime(model.PlanEndTime);
            ar.State = model.State;
            ar.ProjectID = model.ProjectID;
            ar.OperatorID = model.OperatorID;
            ar.OperatorName = model.OperatorName;
            ar.IsTop = model.IsTop ? 1 : 0;
            ar.Type = model.Type;


            for (int i = 0; i < Request.Files.Count; i++)
            {
                if (Request.Files[i].ContentLength == 0) continue;
                string path = AppDomain.CurrentDomain.BaseDirectory + "uploads\\";
                string filename = Guid.NewGuid().ToString() + Path.GetExtension(Request.Files[i].FileName);

                Request.Files[i].SaveAs(Path.Combine(path, filename));

                ar.Images = filename;
            }

            ExecuteResult result;
            if (model.ID == 0)
            {
                ar.CreateTime = DateTime.Now;
                ar.CreateUserID = Config.CurrentOperator.UserID;
                ar.CreateUserName = Config.CurrentOperator.Name;
                ar.OwnerID = Config.CompanyID;
                ar.ParentID = model.ParentID;
                result = TaskService.CreateTask(ar);
            }
            else
            {
                result = TaskService.ModifyTask(ar);
            }

            if (result.ResultNo == 1)
            {
                if (model.act == "save2add")
                {
                    return RedirectToAction("Edit", new { ParentID = model.ParentID });
                }
                else
                    return new CloseWindowResult();
                //model.Message = "添加成功！";
                //model.MessageType = MessageType.correct;
                //return RedirectToAction("Edit", new { ID = ar.ID, Message = model.Message, MessageType = (int)model.MessageType });
            }
            else
            {
                model.Message = "修改失败！";
                model.MessageType = MessageType.error;
                return RedirectToAction("Edit", new { ID = ar.ID, Message = model.Message, MessageType = (int)model.MessageType });
            }

        }

        public ActionResult View(int id)
        {
            ArticleModel model = new ArticleModel();
            model.ID = id;
            model.PracticalStartTime = model.PracticalStartTime == null ? DateTime.Now.ToShortDateString() : model.PracticalStartTime;
            model.PracticalEndtTime = model.PracticalEndtTime == null ? DateTime.Now.ToShortDateString() : model.PracticalEndtTime;
            model.PlanStartTime = model.PlanStartTime == null ? DateTime.Now.ToShortDateString() : model.PlanStartTime;
            model.PlanEndTime = model.PlanEndTime == null ? DateTime.Now.ToShortDateString() : model.PlanEndTime;


            Article ar = arBll.GetArticleByID(model.ID);
            model.Article = ar;


            model.Title = ar.Title;
            model.Content = ar.Content;
            model.PracticalStartTime = FormatTime(ar.PracticalStartTime);
            model.PracticalEndtTime = FormatTime(ar.PracticalEndtTime);
            model.PlanStartTime = FormatTime(ar.PlanStartTime);
            model.PlanEndTime = FormatTime(ar.PlanEndTime);
            model.State = ar.State;
            model.ProjectID = ar.ProjectID;
            model.OperatorID = ar.OperatorID;
            model.CreateUserName = ar.CreateUserName;
            model.CreateTime = ar.CreateTime;
            model.Images = ar.Images;
            model.IsTop = ar.IsTop == 1 ? true : false;

            Account acc = BusinessFactory.Account.GetAccount(ar.OperatorID);
            if (acc != null)
            {
                model.OperatorName = acc.Name;

            }


            model.replyArticles = arBll.GetArticleByReplyID(model.ID);

            Session["ArticleModel"] = model;
            return View(model);
        }

        /// <summary>
        /// 回复任务
        /// </summary>
        /// <param name="id"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult doReplyTask(int id, string content)
        {
            Article art = new Article();
            art.ReplyID = id;
            art.Content = content;
            art.CreateUserID = Config.CurrentOperator.UserID;
            art.CreateUserName = Config.CurrentOperator.Name;
            art.CreateTime = DateTime.Now;

            TaskService.CreateTask(art);

            string url = "/Bug/View?ID=" + id;
            return Redirect(url);
        }

        public ActionResult BugPrint(ArticleModel model)
        {
            return View(model);
        }

        /// <summary>
        /// MAIL发送
        /// </summary>
        /// <returns></returns>
        public void SendMailToClient(int operatorID, string operatorName)
        {
            Session["ViewHtml"] = GetPartialViewHtml();
            Account acc = BusinessFactory.Account.GetAccount(operatorID);
            if (acc.EMail != null)
            {
                string from = Config.MailHost;
                string To = acc.EMail;
                string mailPwd = Config.mailPassword;
                string mailContent = Session["ViewHtml"].ToString();
                System.Net.Mail.SmtpClient client = new SmtpClient("smtp.qq.com");
                client.UseDefaultCredentials = false;
                client.Credentials = new System.Net.NetworkCredential(from, mailPwd);
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                MailAddress addressFrom = new MailAddress(from, Config.CurrentOperator.CompanyName);
                MailAddress addressTo = new MailAddress(To, acc.Name);

                System.Net.Mail.MailMessage message = new MailMessage(addressFrom, addressTo);
                message.Sender = new MailAddress(from);
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.IsBodyHtml = true;
                message.Subject = "软件开发BUG";
                message.Body = mailContent;
                client.Send(message);
            }

        }

        /// <summary>
        /// 获取打印HTML代码 
        /// </summary>
        /// <returns></returns>
        public string GetPartialViewHtml()
        {
            BugController ctrl = new BugController();
            ctrl.ControllerContext = this.ControllerContext;
            ArticleModel model = (ArticleModel)Session["ArticleModel"];
            string html = this.RenderPartialViewToString(ctrl, "~/Views/Bug/BugPrint.cshtml", model);
            return html;
        }

        public string RenderPartialViewToString(Controller controller, string viewName, object model)
        {
            controller.ViewData.Model = model;
            try
            {
                using (StringWriter sw = new StringWriter())
                {
                    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                    ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                    viewResult.View.Render(viewContext, sw);

                    return sw.GetStringBuilder().ToString();
                }
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
    }
}